var app = getApp();
var api = require("../../api.js")
Page({
  /** 页面的初始数据 */
  data: {
    act_title: '',
    act_img: '',
    url_qCord:null, /** 二维码 */
    qCord:null
  },
  /** 生命周期函数--监听页面加载 */
  onLoad: function(options) {
    wx.showLoading({
      title: "二维码生成中..."
    });

    var that = this
    /** 获取当前页面的二维码 */
    var t = new Object();
    var open_id = app.globalData.wxUserInfo.openId;
    t.path = options.path + '?id=' + options.act_id + '&invite_open_id=' + open_id;
    wx.request({
      url: api.wx.qrCode,
      data: t,
      success: function (res) {
        console.log(res)
        if (res.statusCode == 200 && res.data.code == 200 ) {
          that.setData({
            url_qCord: res.data.data,
          })
        }
      }
    });
    // 获取设备宽高，以备海报全屏显示
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          windowW: res.windowWidth,
          windowH: res.windowHeight,
          act_img: options.act_img,
          act_title: options.act_title
        })
      },
    })
    console.log('act_img -->  ' + options.act_img)
    // 海报背景图线上地址
    var url = 'https://qiniu.v2too.com/bk_hb.jpg'
    // 活动图片
    var urll = options.act_img;

    setTimeout(() => {
      // 小程序二维码
      var urlqCord = 'https://qiniu.v2too.com/kdld_ewm.jpg';
      if (this.data.url_qCord != null) {
        urlqCord = this.data.url_qCord
      }
      console.log('urlqCord -- > ' + urlqCord)
      that.getBG(url).then(function (locationData) {
        that.setData({
          bgpic: locationData
        })
      })
      that.getBG(urll).then(function (locationData) {
        that.setData({
          propic: locationData
        })
      })
      // 小程序二维码
      that.getBG(urlqCord).then(function (locationData) {
        that.setData({
          qCord: locationData
        })
      })
    },800)
  },
  onShow: function() {
    setTimeout(() => {
      wx.canvasToTempFilePath({
        canvasId: 'firstCanvas',
        success: (res) => {
          this.drawCanvas()
        }
      }, this)
      wx.hideLoading()
    }, 1200)
  },
  // 绘制canvas
  drawCanvas() {
    var that = this
    var windowW = that.data.windowW
    var windowH = that.data.windowH
    var text = that.data.act_title
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = wx.createCanvasContext('firstCanvas', this)
    //填充背景
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, 310, 490);
    //绘制活动图片
    ctx.drawImage(that.data.propic, 0, 0, 310, 260);
    //绘制标题
    ctx.setFontSize(18);
    ctx.setFillStyle('#000000');
    //ctx.fillText(text, 10, 285);
    var row = that.newLine(text, ctx)
    var a = 24 //定义行高25
    for (var i = 0; i < row.length; i++) {
      ctx.setFontSize(18)
      ctx.setFillStyle("#000000")
      ctx.fillText(row[i], 30, 285 + a * i, 320)
    }
    //绘制房子地址
    // ctx.setFontSize(13);
    // ctx.setFillStyle('#6F6F6F');
    // ctx.fillText('中国', 10, 310);

    //绘制房子价格
    // const metrics = ctx.measureText(5200); //测量文本信息
    // ctx.stroke();
    // ctx.rect(10, 328, metrics.width + 30, 25);
    // ctx.setFillStyle('rgba(20,136,204,1)');
    // ctx.fill();
    // ctx.setFillStyle('#FFFFFF');
    // ctx.fillText('￥5000', 15, 345);

    //房源浏览量
    // ctx.setFillStyle('#6F6F6F');
    // ctx.fillText('1000＋  views', 215, 345)

    //绘制一条虚线
    ctx.strokeStyle = '#5BC7F6';
    ctx.beginPath();
    ctx.setLineWidth(1);
    ctx.setLineDash([2, 4]);
    ctx.moveTo(10, 365);
    ctx.lineTo(300, 365);
    ctx.stroke();

    //绘制介绍(以及二维码)
    ctx.setFontSize(12.5);
    ctx.setFillStyle('#aaaaaa');
    ctx.fillText('长按识别小程序码', 10, 414);
    ctx.fillText('分享更多优惠', 10, 443);
    ctx.drawImage(that.data.qCord, 205, 382, 90, 90);
    ctx.draw();

  },

  // 点击保存按钮，同时将画布转化为图片
  daochu: function() {
    var that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      canvasId: 'firstCanvas',
      fileType: 'jpg',
      quality: 1,
      success: function(res) {
        that.setData({
          shareImage: res.tempFilePath
        })
        that.eventSave();
        // setTimeout(function () {
        //   wx.showModal({
        //     title: '提示',
        //     content: '将生成的海报保存到手机相册，可以发送给微信好友或分享到朋友圈',
        //     success(res) {
        //       if (res.confirm) {
        //         that.eventSave()
        //       } else if (res.cancel) {
        //         console.log('用户点击取消')
        //       }
        //     }
        //   })
        // }, 1000)
      }
    })
  },

  // 将商品分享图片保存到本地
  eventSave() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImage,
      success(res) {
        wx.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
    setTimeout(function() {
      /** 返回上一级页面 */
      wx.navigateBack({
        delta: 1
      })
    }, 1000)
  },

  //将线上图片地址下载到本地，此函数进行了封装，只有在需要转换url的时候调用即可
  getBG(url) {
    // Promise函数给我很大的帮助，让我能return出回调函数中的值
    return new Promise(function(resolve) {
      wx.downloadFile({
        url: url,
        success: function(res) {
          url = res.tempFilePath
          resolve(url);
        }
      })
    })
  },

  // canvas多文字换行
  newLine(txt, context) {
    var txtArr = txt.split('')
    var temp = ''
    var row = []
    for (var i = 0; i < txtArr.length; i++) {
      if (context.measureText(temp).width < 230) {
        temp += txtArr[i]
      } else {
        i--
        row.push(temp)
        temp = ''
      }
    }

    row.push(temp)
    //如果数组长度大于3 则截取前三个
    if (row.length > 3) {
      var rowCut = row.slice(0, 3);
      var rowPart = rowCut[2];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 180) {
          test += rowPart[a];
        } else {
          break;
        }
      }

      empty.push(test);
      var group = empty[0] + "..." //这里只显示三行，超出的用...表示
      rowCut.splice(2, 1, group);
      row = rowCut;
    }
    return row
  },

})